package com.atguigu.grainmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.grainmall.cart.feign.ProductFeignService;
import com.atguigu.grainmall.cart.interceptor.CartInterceptor;
import com.atguigu.grainmall.cart.service.CartService;
import com.atguigu.grainmall.cart.to.UserInfoTo;
import com.atguigu.grainmall.cart.vo.Cart;
import com.atguigu.grainmall.cart.vo.CartItem;
import com.atguigu.grainmall.cart.vo.SkuInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author shiyuan
 * @Date 2023/3/16 9:26
 * @Version 1.0
 **/
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 购物车使用键的前缀
     */
    private final String CART_PREFIX = "grainmall:cart";

    /**
     * 将商品添加到购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 获取到要进行操作的购物车
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        String result = (String) cartOperations.get(skuId.toString());
        // 判断当前商品是否在购物车中存在
        if (StringUtils.isEmpty(result)){
            // 商品添加到购物车
            CartItem cartItem = new CartItem();
            // 采用线程池异步编排 执行两个远程调用操作 节约时间快速多线程查询
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 远程查询当前要查询商品的信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
                cartItem.setSkuId(skuId);
            },executor);

            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                // 远程查询相互sku商品的组合信息
                List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
                cartItem.setSkuAttr(skuSaleAttrValue);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValuesTask).get();

            // 存入redis默认序列化是字符流形式，换成json字符串的形式保存
            String s = JSON.toJSONString(cartItem);
            cartOperations.put(skuId.toString(),s);

            return cartItem;
        }
        else {
            // 存在就直接 将数量叠加
            CartItem cartItem = JSON.parseObject(result, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            String jsonString = JSON.toJSONString(cartItem);
            // 存入redis
            cartOperations.put(skuId.toString(),jsonString);
            return cartItem;
        }

    }

    /**
     * 获取购物车中的某一个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        String str = (String) cartOperations.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);

        return cartItem;
    }

    /**
     * 获取购物车信息
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        // 判断是否为登陆的购物车
        if (userInfoTo.getUserId() != null){
            // 登陆状态 获取购物车
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            // 如果临时购物车中有的数据还没有 就进行合并
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null){
                // 临时购物车有数据，就需要要合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                // 清空合并后的临时购物车
                clearCart(tempCartKey);
            }
            // 获取登陆后购物车的数据(包含临时购物车数据)
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else {
            // 未登录状态获取购物车
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 获取临时购物车
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 清空购物车数据
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物车中的商品项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String jsonString = JSON.toJSONString(cartItem);
        cartOperations.put(skuId.toString(),jsonString);
    }

    /**
     * 增减数量按钮处理,修改购物车购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        cartItem.setCount(num);
        String jsonString = JSON.toJSONString(cartItem);
        cartOperations.put(skuId.toString(),jsonString);
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        cartOperations.delete(skuId.toString());
    }

    /**
     * 获取购物车中的购物项
     * @return
     */
    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() == null){
            // 没登陆
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            // 获取已选中的购物项
            List<CartItem> cartItemList = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item->{
                        // 更新为最新价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());
            return cartItemList;
        }
    }

    /**
     * 获取购物车中的所有购物项
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0){
            List<CartItem> cartItemList = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemList;
        }
        return null;
    }

    /**
     * 获取到要进行操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOperations() {
        // 从拦截器获取登录信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey = "";
        // 是否为临时购物车 确定用的那个键
        if (userInfoTo.getUserId() != null){
            // grainmall:cart:1 以登陆购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            // grainmall:cart:1 未登陆临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // 根据键 操作购物车 使用绑定键操作方法 进行增删改查
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
